package cn.lili.modules.lucene;

import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexNotFoundException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.SearcherFactory;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.store.Directory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.IOException;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 15:42 2025/6/23
 */
@Slf4j
@Component
@DependsOn("onDemandIndexInitializer")
public class SearcherManagerProvider implements InitializingBean, DisposableBean {
    private final Directory directory;
    private final SearcherFactory searcherFactory;
    private volatile SearcherManager searcherManager;

    @Autowired
    public SearcherManagerProvider(Directory directory) {
        this.directory = directory;
        this.searcherFactory = new SearcherFactory();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initializeManager();
    }

    @Override
    public void destroy() throws Exception {
        if (searcherManager != null) {
            searcherManager.close();
            log.info("SearcherManager 已关闭");
        }
    }

    public SearcherManager get() throws IOException {
        if (searcherManager == null) {
            synchronized (this) {
                if (searcherManager == null) {
                    initializeManager();
                }
            }
        }
        return searcherManager;
    }

    private void initializeManager() throws IOException {
        if (searcherManager != null) {
            searcherManager.close();
        }

        try {
            // 尝试打开现有索引
            DirectoryReader reader = DirectoryReader.open(directory);
            searcherManager = new SearcherManager(reader, searcherFactory);
            log.info("成功打开现有索引");
        } catch (IndexNotFoundException e) {
            log.warn("索引不存在，创建空索引: {}", e.getMessage());
            createEmptyIndex();
            DirectoryReader reader = DirectoryReader.open(directory);
            searcherManager = new SearcherManager(reader, searcherFactory);
            log.info("空索引创建成功");
        }
    }
    private void createEmptyIndex() throws IOException {
        try (IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(new IKAnalyzer(true)))) {
            writer.commit();
            log.info("创建空索引完成");
        }
    }

    /**
     * 刷新搜索管理器
     */
    public void refresh() throws IOException {
        if (searcherManager != null) {
            searcherManager.maybeRefresh();
        }
    }

    /**
     * 强制刷新搜索管理器
     */
    public void forceRefresh() throws IOException {
        if (searcherManager != null) {
            searcherManager.maybeRefreshBlocking();
        }
    }
}

